import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { Layout, Menu, Tabs, Dropdown, Popover } from 'antd';
import { FullscreenOutlined, FullscreenExitOutlined } from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';
import { useSearchParams, useNavigate, useLocation, Outlet } from 'react-router-dom';
import { handleIncrementPanes, changeCurrentPane, handelChangeTheme } from 'src/redux/actions/portal';
import { toggleFullscreen } from 'src/utils/fullscreen';
import Header from 'src/components/Portal/Header'
import SliderMenu from 'src/components/Portal/SliderMenu'
import styles from './index.module.less';
import RouterView from 'src/router/RouterView';
const { Sider } = Layout;
const { TabPane } = Tabs;

const Portal = () => {
    const navigate = useNavigate();

    const { pathname } = useLocation();

    const [collapsed, setCollapsed] = useState(false);
    const [fullScreened, setFullScreened] = useState(false)
    const { panes, menus, currentPane, theme } = useSelector((state) => state.portal);

    const dispatch = useDispatch()
    // 设置tab
    const setPanes = useCallback((payload) => {
        dispatch(handleIncrementPanes(payload))
    },
        [dispatch]
    )
    // url改变设置当前的tab高亮
    useEffect(() => {
        if (pathname.startsWith('/portal/')) {
            dispatch(changeCurrentPane(pathname.replace('/portal/', '')))
        }
    }, [pathname])

    /**
     * tab改变，页面跳转到对应页面
     * @param {*} activeKey 
     */
    function handleTabChange(activeKey) {
        navigate(activeKey)
        dispatch(changeCurrentPane(activeKey))
    }
    /**
     * tab增加或移除
     * @param {*} targetkey 
     * @param {*} action 
     */
    function handleTabEdit(targetkey, action) {
        if (action === 'add') {
            addTab({ key: targetkey })
        } else if (action === 'remove') {
            closeTab(targetkey)
        }
    }
    /**
     * 打开新tab
     * @param {*} newPane 
     */
    function addTab(newPane) {

        const index = panes.findIndex(item => item.key === newPane.key)
        if (index === -1) {
            const newPanes = [...panes, newPane];
            setPanes(newPanes);
        }
        navigate(newPane.path)
        dispatch(changeCurrentPane(newPane.key))
    }
    /**
     * 关闭tab
     * @param {*} targetkey 
     */
    function closeTab(targetkey) {
        let newActiveKey = currentPane;
        let lastIndex = panes.findIndex(pane => pane.key === targetkey) - 1;
        const newPanes = panes.filter(pane => pane.key !== targetkey);
        if (newPanes.length && newActiveKey === targetkey) {
            if (lastIndex >= 0) {
                newActiveKey = newPanes[lastIndex].key;
            } else {
                newActiveKey = newPanes[0].key;
            }
        }
        setPanes(newPanes);
        navigate(newActiveKey)
        dispatch(changeCurrentPane(newActiveKey))
    }
    /**
     * 关闭其他tab
     * @param {*} targetkey 
     */
    function closeOtherTab(targetkey) {
        let newActiveKey = currentPane;

        const newPanes = panes.filter(pane => (pane.key === targetkey || pane.closable === false));

        let lastIndex = newPanes.findIndex(pane => pane.key === targetkey);
        if (newPanes.length) {
            if (lastIndex >= 0) {
                newActiveKey = newPanes[lastIndex].key;
            } else {
                newActiveKey = newPanes[0].key;
            }
        }
        setPanes(newPanes);
        navigate(newActiveKey)
        dispatch(changeCurrentPane(newActiveKey))
    }
    /**
     * 关闭所有tab
     */
    function closeAllTab(targetkey) {
        let newActiveKey = currentPane;
        const newPanes = panes.filter(pane => pane.closable === false);
        let lastIndex = newPanes.findIndex(pane => pane.key === targetkey) - 1;
        if (newPanes.length && newActiveKey === targetkey) {
            if (lastIndex >= 0) {
                newActiveKey = newPanes[lastIndex].key;
            } else {
                newActiveKey = newPanes[0].key;
            }
        }
        setPanes(newPanes);
        navigate(newActiveKey)
        dispatch(changeCurrentPane(newActiveKey))
    }
    /**
     * 点击左侧菜单
     * @param {*} param0 
     */
    function handleSliderMenuItemClick(info, menusItemInfo) {
        const { key } = info
        addTab({
            key,
            path: menusItemInfo.path,
            title: menusItemInfo.title,
            src: menusItemInfo.src,
        })
    }
    // 打开新页签
    const open_new_tab = useCallback((info) => {
        const { path, title, src } = info
        addTab({
            title,
            path,
            src
        })
    }, [])
    /**
     * 点击tabs右键菜单
     * @param {*} param0 
     */
    function handleTabMenuItemClick(key, targetkey) {

        const obj = {
            closeTab: () => { closeTab(targetkey) },
            closeOtherTab: () => { closeOtherTab(targetkey) },
            closeAllTab: () => { closeAllTab(targetkey) },
            refreshTab: () => { refreshTab(targetkey) },
        }
        if (obj[key]) {
            obj[key]()
        }
    }
    /**
     * iframe刷新页面
     * @param {*} node 
     */
    function refreshTab(node) {
        if (node.key.includes('iframe')) {
            window.frames[0].location.reload()
        }
    }

    // 获取tab右键菜单内容
    function getItems(tabBarProps, node) {
        try {
            const pane = tabBarProps.panes.find(item => item.key === node.key) || {};
            const items = [
                {
                    key: 'closeOtherTab',
                    label: '关闭其他',
                    targetkey: node.key
                },
                {
                    key: 'closeAllTab',
                    label: '关闭全部',
                    targetkey: node.key
                },
            ]
            if (pane.props.closable !== false) {
                items.unshift({
                    key: 'closeTab',
                    label: '关闭',
                    targetkey: node.key
                })
            }
            if (!!pane.props.isiframe && tabBarProps.activeKey === node.key) {
                items.push({
                    key: 'refreshTab',
                    label: '刷新页面',
                    targetkey: node.key
                })
            }
            return items
        } catch (error) {

        }
        return []
    }

    /**
     * TabBar渲染修改，增加右键菜单
     * @param {*} props 
     * @param {*} DefaultTabBar 
     * @returns 
     */
    function renderTabBar(tabBarProps, DefaultTabBar) {
        return (
            <DefaultTabBar {...tabBarProps} >
                {
                    (node) => {
                        return (
                            <Dropdown
                                key={node.key}
                                overlay={<Menu
                                    theme={theme}
                                    onClick={(info) => handleTabMenuItemClick(info.key, node.key)}
                                    items={getItems(tabBarProps, node)}
                                />}
                                trigger={['contextMenu']}

                            >
                                <div>{node}</div>
                            </Dropdown >
                        )
                    }
                }
            </DefaultTabBar >
        )
    }

    // 全屏
    const tabBarExtraContent = useMemo(() => {
        return {
            right: <div className={styles.fullscreenContent}>
                <Popover
                    overlayClassName={styles.fullscreenOverlay}
                    placement="bottom"
                    content={fullScreened ? '退出全屏' : '全屏显示'}
                    onClick={() => {
                        setFullScreened(!fullScreened);
                        toggleFullscreen();
                    }}
                    arrowPointAtCenter={true}
                >
                    {fullScreened ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                </Popover>
            </div>
        }
    }, [fullScreened])

    return <Layout>
        <Header
            notifications={[{}]}
            theme={theme}
            setTheme={(v) => dispatch(handelChangeTheme(v))}
        />
        <Layout>
            <Sider
                collapsible
                collapsed={collapsed}
                onCollapse={setCollapsed}
                width={200}
                theme={theme}
                className={styles.slider}
            >
                <SliderMenu
                    menus={menus}
                    theme={theme}
                    onMenuItemClick={handleSliderMenuItemClick}
                    pathname={pathname}
                />
            </Sider>
            <Layout className={styles.content} >
                <div className={styles.tabContainer}>
                    <Tabs
                        type="editable-card"
                        activeKey={currentPane}
                        hideAdd={true}
                        size="small"
                        className={styles.tabs}
                        tabBarExtraContent={tabBarExtraContent}
                        renderTabBar={renderTabBar}
                        onEdit={handleTabEdit}
                        onChange={handleTabChange}
                    >
                        {panes.map(pane => (
                            <TabPane
                                key={pane.key}
                                tab={pane.title}
                                closable={pane.closable}
                                isiframe={!!pane.src} />
                        ))}
                    </Tabs>
                </div>
                <Layout className="content" >
                    <RouterView open_new_tab={open_new_tab} />
                </Layout>
            </Layout>
        </Layout>
    </Layout>
}

export default Portal